from django.shortcuts import render_to_response, get_object_or_404
from Shikimo.pix.models import Photo, Tag
from Shikimo.comments.models import Comment
from Shikimo.comments.forms import CommentForm
from django.db import connection
from Shikimo.pix.models import UserProfile
from django.contrib.auth.models import User
from django.db import connection
def index(request):

    latest = Photo.objects.all().order_by('-datetime')[:10]

    tags = Tag.objects.all()
    
    return render_to_response('front/index.html', {'latest':latest, 'tags':tags})

def viewtag(request,tag_id):

    pics = Photo.objects.filter(tags=tag_id)
    tag = Tag.objects.get(pk=tag_id)
    return render_to_response('front/viewtag.html', {'latest':pics,'tag':tag})
    
def archive(request):
 
    pics = Photo.objects.all()
    
    return render_to_response('front/archive.html', {'latest':pics})

def about(request):

    user = User.objects.all()
    
    # get just the first in the list
    user = user[0]
    
    return render_to_response('front/about.html', {'user':user})
    

def pic(request,pic_id):
   
    pic = Photo.objects.get(pk=pic_id)
    
    data = request.POST
    
    if len(data) == 0:
        form = CommentForm()
    else:
        form = CommentForm(data)
    
    comments = {}
    
    try:
        
     # get comments for current pic
        comments = Comment.objects.filter(photo = pic_id)
        
    
    except:
        # no comments for the current pic, move on
        pass
    
    if (len(data) != 0) and (form.is_valid()):
        # comment form has data and is valid, add new comment
        
        import datetime
        
        newcomment = Comment()
        newcomment.photo = Photo.objects.get(pk = pic_id)
        newcomment.datetime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M')
        newcomment.author = form.cleaned_data['author']
        newcomment.email = form.cleaned_data['email']
        newcomment.website = form.cleaned_data['website']
        newcomment.content = form.cleaned_data['content']
        
       
        newcomment.save()
        
        # unbind the form
        form = CommentForm()
    

    return render_to_response('front/pic.html', {'pic': pic, 'commentform': form, 'comments': comments})

  
